/* 
 * Copyright (c)	Insighten Intelligent Equipment co.,LTD
 * 
 *  Use of this software is controlled by the terms and conditions found
 *  in the license agreement under which this software has been supplied.
 * 
 */
#include <stdlib.h>

#include "rwbuf.h"

RwBuf *buf_new(FunMemAlloc alloc, FunMemFree mfree)
{
	RwBuf *thiz = NULL;

	thiz = calloc(sizeof(RwBuf), 1);

	thiz->mem = NULL;
	thiz->mem_alloc = alloc;
	thiz->mem_free = mfree;

	return thiz;
}

int buf_destroy(RwBuf *thiz)
{
	if (thiz != NULL) {
		if (thiz->mem != NULL) {
			if (thiz->mem_free) {
				thiz->mem_free(thiz->mem);
			} else {
				free(thiz->mem);
			}
			thiz->mem = NULL;
		}
		free(thiz);
		thiz = NULL;
	}
	return 0;
}

int buf_init(RwBuf *thiz, int size)
{
	if (thiz == NULL || size <= 0) {
		return -1;
	}
	if (thiz->mem_alloc) {
		thiz->mem = (char *)thiz->mem_alloc(size);
	} else {
		thiz->mem = calloc(size, 1);
	}
	if (thiz->mem == NULL) {
			return -1;
	}
	thiz->rpos = 0;
	thiz->wpos = 0;
	thiz->totalsize = size;

	return 0;
}

int buf_update_wpos(RwBuf *thiz, int size)
{
	if (thiz != NULL && size >= 0 ) {
		thiz->wpos += (size%(thiz->totalsize+1));
		return 0;
	}
	return -1;
}

int buf_update_rpos(RwBuf *thiz, int size)
{
	if (thiz != NULL && size >= 0) {
		thiz->rpos += (size % (thiz->totalsize+1));
		return 0;
	}
	return -1;
}



